import { _decorator, Asset, assetManager, Component, instantiate, Node, Prefab, resources } from 'cc';
import { BattleBase } from './base/BattleBase';
import { BattleSprite } from './BattleSprite';
import { SpriteFSM } from './SpriteFSM';
import { SpriteState_Idle } from './state/SpriteState_Idle';
import { DyAssetsManager } from '../manager/DyAssetsManager';
const { ccclass, property } = _decorator;

@ccclass('BattleScene')
export class BattleScene extends BattleBase {
    roleNode : Node = null;
    
    protected onLoad(): void {
        this.roleNode = this.node.getChildByName('roles');
    }

    start() {
        // assetManager.loadBundle('sprites',(err, bundle) => {
        //     this.onLoadBundle();
        // });

        this.createHero();
        this.createMonster();

        console.log("roleNode :", this.roleNode);
    }

    onLoadBundle(){
        this.createHero();
        this.createMonster();
    }

    update(deltaTime: number) {
        
    }

    async createHero() {
        let sp = await DyAssetsManager.createPrefabAsync("sprites/sprite_22")
        sp.setParent(this.roleNode);
        let sprite = sp.addComponent(BattleSprite);
        this.onLoadHero(sprite);
    }

    async createMonster() {
        // resources.load("sprites/monster_01",Prefab, (err, prefab) => {
        //     let sp = DyAssetsManager.instantiate(prefab);
        //     sp.setParent(this.roleNode);
        //     let x = Math.random() * 600 - 300;
        //     let y = Math.random() * 300 - 150;
        //     sp.setPosition(x,y,0);
        //     let sprite = sp.addComponent(BattleSprite);
        //     this.onLoadMonster(sprite);
        // })
        let sp = await DyAssetsManager.createPrefabAsync("sprites/monster_01")
        console.log("sp :", sp['prefab']);
        sp.setParent(this.roleNode);
        let x = Math.random() * 600 - 300;
        let y = Math.random() * 300 - 150;
        sp.setPosition(x,y,0);
        let sprite = sp.addComponent(BattleSprite);
        this.onLoadMonster(sprite);

        let sp1 = DyAssetsManager.instantiateNode(sp)

        sp1.setParent(this.roleNode);
        let x1 = Math.random() * 600 - 300;
        let y1 = Math.random() * 300 - 150;
        sp1.setPosition(x1,y1,0);

    }

    onLoadHero(sp:BattleSprite) {
        console.log('onLoadSprite :',sp.node.name);
        this.spriteArray.push(sp);

        this.scheduleOnce(() => {
            let fsm = new SpriteFSM(sp);
            fsm.registState("Idle",new SpriteState_Idle(sp));
            fsm.isOn = true;
        }, 0.01);
    }

    onLoadMonster(sp:BattleSprite) {
        console.log('onLoadSprite :',sp.node.name);
        this.spriteArray.push(sp);

        this.scheduleOnce(() => {
            let fsm = new SpriteFSM(sp);
            fsm.registState("Idle",new SpriteState_Idle(sp));
            fsm.isOn = true;
        }, 0.01);
    }

}


